package com.lm.jasync.service;

import com.github.jasync.sql.db.RowData;
import com.github.jasync.sql.db.mysql.pool.MySQLConnectionFactory;
import com.lm.jasync.entry.SysUserEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class UserService {

    private  MySQLConnectionFactory connectionFactory;

    public UserService(MySQLConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public CompletableFuture<List<SysUserEntity>> findAllUsers() {
        return connectionFactory.create()
                .thenCompose(conn ->
                        conn.sendQuery("SELECT user_id as id, username as name, email FROM sys_user")
                                .thenApply(queryResult -> {
                                    List<SysUserEntity> users = new ArrayList<>();
                                    for (RowData row : queryResult.getRows()) {
                                        SysUserEntity user = new SysUserEntity();
                                        user.setUserId(row.getLong("id"));
                                        user.setUsername(row.getString("name"));
                                        user.setEmail(row.getString("email"));
                                        users.add(user);
                                    }
                                    conn.disconnect();
                                    return users;
                                })
                );
    }
}